#include "include/jwtCode.h"

//生成密码结构体
int jwt_encode(accept_info_t* userinfo,char *username){
    
    char *jwt;
    size_t jwt_length;
    struct l8w8jwt_encoding_params params;
    l8w8jwt_encoding_params_init(&params);
    //加密算法
    params.alg = L8W8JWT_ALG_HS256;

    //用户信息
    params.sub = username;

    //加密密钥
    params.secret_key = (unsigned char*)JWT_SECRET_KEY;
    params.secret_key_length = strlen(JWT_SECRET_KEY);

    printf("JWT_SECRET_KEY bytes: ");
    for (int i = 0; i < strlen(JWT_SECRET_KEY); ++i) {
        printf("%02x ", (unsigned char)JWT_SECRET_KEY[i]);
    }
    printf("\n");
    //输出
    params.out = &jwt;
    params.out_length = &jwt_length;

    int r = l8w8jwt_encode(&params);
    printf("jwt_encode:%s\n",jwt);
    printf("jwt_length:%ld\n",jwt_length);
    strcpy(userinfo->username,username);
    //printf("username:%s\n",userinfo->username);
    strcpy(userinfo->jwt,jwt);
    userinfo->jwt_length=jwt_length;
    //printf("jwt_length:%s\n",userinfo->jwt);

    if(r == L8W8JWT_SUCCESS){
        l8w8jwt_free(jwt);
        return 0;
    }
    

    l8w8jwt_free(jwt);
    return -1;
}



//判断结构体是否合法
int jwt_decode(accept_info_t* userinfo){
    
    struct l8w8jwt_decoding_params dparams;
    l8w8jwt_decoding_params_init(&dparams);
    dparams.jwt = userinfo->jwt;
    dparams.jwt_length = userinfo->jwt_length;
    dparams.alg = L8W8JWT_ALG_HS256;
    dparams.verification_key = (unsigned char*)JWT_SECRET_KEY;
    dparams.verification_key_length = strlen(JWT_SECRET_KEY);
    dparams.validate_typ = NULL;
    dparams.validate_exp = 0;
    enum l8w8jwt_validation_result result;
    int dr = l8w8jwt_decode(&dparams, &result, NULL, NULL);
    printf("decode result: %d, validation: %d\n", dr, result);

    if(dr == L8W8JWT_SUCCESS && result == L8W8JWT_VALID){
        printf("用户身份验证成功\n");
        return 1;
    }
    printf("用户身份验证失败\n");
    return 0;
}


// 与客户端确认连接，并生成结构体
task_t* accept_and_get_task(int netfd,accept_info_t *userinfo){
    //验证用户身份
    int flag = 0;//发送确认信息
    int ret = jwt_decode(userinfo);
    if(ret == 0){
        printf("用户身份验证失败\n");
        close(netfd);
        flag = -1;
        send(netfd,&flag,sizeof(int),0);
        return NULL;
    }
    send(netfd,&flag,sizeof(int),0);
    //创建接收任务
    task_t* task = task_init(netfd);
    recv(netfd,&task->_train,sizeof(task->_train),0);
    printf("task->_train._cmdType:%d\n",task->_train._cmdType);
    printf("task->_train._data:%s\n",task->_train._data);
    return task;
}
